package com.rainbow.commons.mybatis;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import java.io.Serializable;
import java.util.List;

/**
 * @author qlkj on 2018/4/11
 */
public abstract class SuperServiceImpl<M extends BaseMapper<T>, T extends SuperEntity> extends ServiceImpl<M, T> implements ISuperService<T> {

    @Override
    public Boolean beforeInsert(T entity) {
        return true;
    }

    @Override
    public Boolean beforeInsertBatch(List<T> entityList) {
        //entityList.forEach();
        return true;
    }

    @Override
    public Boolean beforeUpdate(T current, T entity) {
        if (current == null) {
            System.err.println("无法更新，没有查询到记录");
        }
        return true;
    }

    @Override
    public Boolean beforeDelete(T current) {
        if (current == null) {
            System.err.println("无法删除，没有查询到记录");
        }
        return true;
    }

    @Override
    public void afterInsert(T entity) {

    }

    @Override
    public void afterInsertBatch(List<T> entityList) {

    }

    @Override
    public void afterUpdate(T entity) {

    }

    @Override
    public void afterDelete(T current) {

    }

    /**
     * 新增数据
     *
     * @param entity
     * @return
     */
    @Override
    public boolean insert(T entity) {
        if (beforeInsert(entity)) {
            Boolean result = super.insert(entity);
            if (result) {
                afterInsert(entity);
            }
        }
        return false;
    }

    /**
     * 更新数据
     *
     * @param entity
     * @return
     */
    @Override
    public boolean updateById(T entity) {
        T current = selectById(entity.getId());
        if (beforeUpdate(current, entity)) {
            Boolean result = super.updateById(entity);
            afterUpdate(entity);
            return result;
        }
        return false;
    }

    /**
     * 数据数据
     *
     * @param id
     * @return
     */
    @Override
    public boolean deleteById(Serializable id) {

        T current = selectById(id);

        if (beforeDelete(current)) {
            Boolean result = super.deleteById(id);

            afterDelete(current);

            return result;
        }
        return false;
    }
}
